package cn.hhy.hrm.userdetails;

import cn.hhy.hrm.Exception.ErrorCode;
import cn.hhy.hrm.Exception.ValidUtils;
import cn.hhy.hrm.domain.LoginUser;
import cn.hhy.hrm.domain.Permission;
import cn.hhy.hrm.service.ILoginUserService;
import cn.hhy.hrm.service.IPermissionService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


@Component
public class UserDetailsServiceImpl implements
        UserDetailsService {

    @Autowired
    private ILoginUserService loginUserService;
    @Autowired
    private IPermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ValidUtils.assertNotEmpty(username, ErrorCode.CODE_400_PARAM_VALID);

        LoginUser loginUser = loginUserService.selectOne(new EntityWrapper<LoginUser>().eq("username", username));

        if (loginUser==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Permission> permissions = permissionService.selectByUserId(loginUser.getEid());
        System.out.println(permissions);


        List<GrantedAuthority> authorities=permissions.stream().map(permission-> new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());
        String s = JSON.toJSONString(loginUser);

        return new User(
                s,
                loginUser.getPassword(),
                true,
                true,
                true,
                true,
                authorities
        );
    }
}
